package com.wman.lib;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wman.sheep.common.utils.TLog;
import com.wman.sheep.common.utils.ToastUtil;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import io.reactivex.functions.Consumer;

/**
 * Name     youcai
 * Anthor   wman
 * Time     2019/08/18 0018 23:34
 * Describe 启动页面
 */
public class SplashActivity extends FragmentActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getPermissions();
    }

    /**
     * 获取运行时权限
     */
    private void getPermissions() {
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.requestEach(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Permission>() {
                    boolean isDeniy = false;

                    @Override
                    public void accept(Permission permission) throws Exception {
                        TLog.d("获取运行时权限 Permission result :" + permission);
                        if (permission.granted) {
                            startAction();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            isDeniy = true;
                        } else {
                            isDeniy = true;
                        }
                        if (isDeniy) {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            ToastUtil.showTextToast("获取定位失败，该功能不能正常使用！");
//                            startAction();
                        }
                    }
                });
    }

    private void startAction() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish();
            }
        }, 2000);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }
}
